package com.jinyijia.api.rest.v1;

import com.jinyijia.api.rest.v1.dto.CategoryDTO;
import com.jinyijia.api.rest.v1.vo.CategoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * @author WX
 * @date 2018/8/7
 **/
@RestController
@RequestMapping("/categories")
public class CategoryController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 分类列表
     *
     * @return
     */
    @GetMapping("/categories")
    public List<CategoryVO> getCategories() {
        List<CategoryDTO> categoryDTO = restTemplate.exchange("http://category-service/categories", HttpMethod.GET, null, new ParameterizedTypeReference<List<CategoryDTO>>() {
        }).getBody();
        List<CategoryVO> categoryVOS = new ArrayList<>();
        categoryDTO.stream().forEach(categoryDTO1 -> {
            categoryDTO1.getChildren().stream().forEach(c -> {
                categoryVOS.add( new CategoryVO(c.getId(),c.getName(),c.getSort()));
            });
        });
        Collections.sort(categoryVOS);
        return categoryVOS;
    }

    /**
     * 分类查询商品
     *
     * @return
     */
    @GetMapping("/goods")
    public Object getCategoryGoods(Integer categoryId) {
        return restTemplate.getForObject("http://goods-service/goods?categoryId={1}", Object.class, categoryId);
    }
}
